//
//  StyleViewController.m
//  OneDay
//
//  Created by lanou3g on 15/10/27.
//  Copyright © 2015年 oneDay. All rights reserved.
//

#import "StyleViewController.h"
#import "StyleCollectionViewCell.h"
#import "CityTableViewController.h"
#import "StyleTViewController.h"
#import "PartyTableViewCell.h"
#import "StyleNextViewController.h"
#import "HJCarouselViewLayout.h"
#import "PartyDetailViewController.h"
#import <Reachability/Reachability.h>


@interface StyleViewController ()<UICollectionViewDataSource, UICollectionViewDelegate,UITableViewDataSource,UITableViewDelegate,UICollectionViewDelegateFlowLayout,SDCycleScrollViewDelegate>

#pragma mark -- collection的属性
@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) NSMutableArray *collectionDataArray;

#pragma mark -- 顶部轮播图
// 轮播图
@property (nonatomic, strong) SDCycleScrollView *sdScrollView;
// web轮播图片数组
@property (nonatomic, strong) NSMutableArray *webImageArray;
// 数据数组
@property (nonatomic, strong) NSMutableArray *styleWebArray;

#pragma mark -- 总表头
@property (nonatomic, strong) UIView *headerView;

#pragma mark -- tableView的属性
@property (nonatomic, assign) NSInteger page;
@property (nonatomic, strong) NSMutableArray *partyDataArray;

@end

@implementation StyleViewController



- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"OneDay活动";
    self.navigationController.navigationBar.translucent = NO;
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationController.navigationBar.translucent = NO;
    
    // 开启网络链接
    Reachability *reach = [Reachability reachabilityWithHostname:@"www.apple.com"];
    // 开启一个通知 来监听网络状态的改变
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];
    // 开启网络监控
    [reach startNotifier];
}
// 判断网络状态
- (void)isHaveWifi
{
    // 开启网络链接
    Reachability *reach = [Reachability reachabilityWithHostname:@"www.apple.com"];
    // 开启一个通知 来监听网络状态的改变
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];
    // 开启网络监控
    [reach startNotifier];
}

- (void)reachabilityChanged:(NSNotification *)changed
{
    /*
     网络是否链接 -- isReachable
     WiFi ---- isReachableViaWiFi
     2G,3G --- isReachableViaWWAN
     */
    // 获取 View 里开启的哪个网络连接
    Reachability *reach = [changed object];
    if (![reach isReachable]) {
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:@"小天检测到您没有开启网络哦😭" preferredStyle:UIAlertControllerStyleAlert];
        // 创建一个ok按钮
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"我要去开网!!!" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
            NSLog(@"%@", action.title);
        }];
        [alertController addAction:okAction];
        [self presentViewController:alertController animated:YES completion:nil];
    }else {
        [self addCollectionView];
        [self addRightButtonItem];
        
        // 1、顶部轮播图请求数据
        [self requestStylePhotoDataWithUrl:kStylePhoto block:^() {
            self.webImageArray = [NSMutableArray array];
            for (StyleNextTableViewModel *model in self.styleWebArray) {
                [self.webImageArray addObject:model.photo];
            }
            [self.tableView reloadData];
            [self addScrollViewWithImageArray:self.webImageArray];
            
        }];
        // 中部collection请求数据
        [self requestMainStyleDataWithUrl:kStyleUrl block:^() {
            [self.collectionView reloadData];
        }];
        // tabelView请求数据
        self.page = 1;
        NSString *partyUrl = [kParty stringByAppendingString:[NSString stringWithFormat:@"&page=%ld&lat=40.030613",self.page]];
        self.partyDataArray = [NSMutableArray array];
        [self requestFirstPartyDataWithUrl:partyUrl block:^(NSArray *array) {
            [self.partyDataArray addObjectsFromArray:array];
            [self.tableView reloadData];
        }];
        // Do any additional setup after loading the view.
        
        // 刷新数据
        [self setUp];
    }
}




#pragma mark -- 顶部轮播图
- (void)addScrollViewWithImageArray:(NSMutableArray *)array
{
    self.sdScrollView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, kWidth, 0.66 * kWidth) imageURLStringsGroup:array];
    
    
    // 几秒钟换图
    self.sdScrollView.autoScrollTimeInterval = 3;
    
    // 小圆点的颜色
    self.sdScrollView.dotColor = [UIColor clearColor];
    // 小圆点的位置在中间还是右边
    self.sdScrollView.pageControlAliment = SDCycleScrollViewPageContolAlimentRight;
    // 设置代理
    self.sdScrollView.delegate = self;
    [self.headerView addSubview:self.sdScrollView];
}

// 唯一的代理方法  选中图片执行
- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index
{
    NSLog(@"点击选中的第%ld张.", index + 1);
    StyleNextViewController *styleNextVC = [[StyleNextViewController alloc] init];
    styleNextVC.model = self.styleWebArray[index];
    styleNextVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:styleNextVC animated:YES];
}


#pragma mark -- 添加rightBarButotnItem
- (void)addRightButtonItem
{
    UIBarButtonItem *right = [[UIBarButtonItem alloc] initWithTitle:@"城市>" style:UIBarButtonItemStylePlain target:self action:@selector(rightAction:)];
    right.tintColor = [UIColor colorWithRed:0.5 green:0.4 blue:0.35 alpha:1];
    self.navigationItem.rightBarButtonItem = right;
}
- (void)rightAction:(UIBarButtonItem *)sender
{
    CityTableViewController *cityVC = [[CityTableViewController alloc] init];
    [self.navigationController pushViewController:cityVC animated:YES];
}

#pragma mark -- 添加CollectionView
- (void)addCollectionView
{
    self.tableView = [[UITableView alloc] initWithFrame:[UIScreen mainScreen].bounds style:UITableViewStylePlain];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    [self.view addSubview:self.tableView];
    // 没有数据的时候为白色，没有线条
    self.tableView.separatorStyle = NO;
    // 设置表头
    self.headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kWidth, kWidth)];
    self.tableView.tableHeaderView = self.headerView;
     
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    [flowLayout setItemSize:CGSizeMake(0.2 * kWidth, 0.11 * kWidth)];//设置cell的尺寸
    [flowLayout setScrollDirection:UICollectionViewScrollDirectionVertical]; //布局方向
    CGFloat kx = 0.04 * kWidth;
    flowLayout.sectionInset = UIEdgeInsetsMake(kx, kx, kx, kx);// 1、3距离顶部底部距离，2、4控制cell间距
    
    _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0.66 * kWidth, kWidth, 0.34 * kWidth) collectionViewLayout:flowLayout];
    _collectionView.backgroundColor = [UIColor colorWithRed:194 / 255.0 green:240 / 255.0 blue:244 / 255.0 alpha:1];
    // 设置代理
    _collectionView.dataSource = self;
    _collectionView.delegate = self;
    // 注册cell
    static NSString *idrntifier = @"CollectionViewCell";
    [_collectionView registerClass:[StyleCollectionViewCell class] forCellWithReuseIdentifier:idrntifier];
    
    [self.tableView.tableHeaderView addSubview:_collectionView];
}

// cell数目
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.collectionDataArray.count;
}

// 设置collection的cell
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"CollectionViewCell";
    StyleCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
    if (self.collectionDataArray.count > 0) {
        MainStyleModel *model = self.collectionDataArray[indexPath.row];
        cell.label.text = model.cn_name;
        return cell;
    }
    return nil;
}

// cell跳转方法
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    MainStyleModel *model = self.collectionDataArray[indexPath.row];
    StyleTViewController *styleTVC = [[StyleTViewController alloc] init];
    styleTVC.needStr = model.name;
    [self.navigationController pushViewController:styleTVC animated:YES];
}

#pragma mark -- tableView的代理方法
// tableView的cell数目
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.partyDataArray.count;
}
//设置Cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"PartyTableViewCell";
    PartyTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[PartyTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    // 取消分割线
    self.tableView.separatorStyle = NO;
    // 取消选中的颜色
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    PartyModel *model = self.partyDataArray[indexPath.row];
    cell.model = model;
    return cell;
}

// 设置cell的高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 0.85 * kWidth;
}

// tableView 的cell点击方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    PartyDetailViewController *detailVC = [[PartyDetailViewController alloc] init];
    PartyModel *model = self.partyDataArray[indexPath.row];
    detailVC.leo_id = model.leo_id;
    [self.navigationController pushViewController:detailVC animated:YES];
    
}

#pragma mark -- 刷新数据
// 界面出现的时候结束刷新
- (void)viewWillAppear:(BOOL)animated
{
    
    [self.tableView.header endRefreshing];
}
- (void)setUp
{
    // 下拉刷新
    self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(headerRefresh)];
    self.tableView.footer = [MJRefreshBackFooter footerWithRefreshingTarget:self refreshingAction:@selector(footerRefresh)];
    // 进入刷新状态
    [self.tableView.header beginRefreshing];
}
- (void)footerRefresh
{
    _page++;
    NSString *partyUrl = [kParty stringByAppendingString:[NSString stringWithFormat:@"&page=%ld&lat=40.030613",self.page]];
    [self requestFirstPartyDataWithUrl:partyUrl block:^(NSArray *array) {
        [self.partyDataArray addObjectsFromArray:array];
        [self.tableView reloadData];
    }];
    [self.tableView.footer endRefreshing];
    
}

- (void)headerRefresh
{
    self.page = 1;
    // 在这个方法中请求数据
    [self.tableView reloadData];
    // 结束刷新状态
    [self.tableView.header endRefreshing];
}

#pragma mark -- 请求数据

#pragma mark -- 顶部轮播图请求数据
- (void)requestStylePhotoDataWithUrl:(NSString *)url block:(void(^)(void))block
{
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSMutableURLRequest *requset = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30];
        [requset setHTTPMethod:@"GET"];
        
        NSURLSessionConfiguration *config = [NSURLSessionConfiguration ephemeralSessionConfiguration];
        NSURLSession *session = [NSURLSession sessionWithConfiguration:config];
        NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:requset completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            
            if (data == nil) {
                return;
            }
            
            NSDictionary *rootDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            NSMutableArray *array = rootDic[@"data"];
            self.styleWebArray = [NSMutableArray array];
            for (NSDictionary *dic in array) {
                StyleNextTableViewModel *model = [[StyleNextTableViewModel alloc] init];
                [model setValuesForKeysWithDictionary:dic];
                [self.styleWebArray addObject:model];
            }
            
            dispatch_async(dispatch_get_main_queue(), ^{
                block();
            });
        }];
        [dataTask resume];
    });
}
#pragma mark -- 中部collection请求数据
- (void)requestMainStyleDataWithUrl:(NSString *)url block:(void(^)())block
{
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]  cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30];
        [request setHTTPMethod:@"GET"];
        
        NSURLSessionConfiguration *config = [NSURLSessionConfiguration ephemeralSessionConfiguration];
        NSURLSession *session = [NSURLSession sessionWithConfiguration:config];
        NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            
            if (data == nil) {
                return ;
            }
            
            NSDictionary *rootDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            NSArray *array = rootDic[@"result"];
            NSMutableArray *tempArray = [NSMutableArray array];
            for (NSDictionary *dic in array) {
                MainStyleModel *model = [[MainStyleModel alloc] init];
                [model setValuesForKeysWithDictionary:dic];
                [tempArray addObject:model];
            }
            if (tempArray.count > 0) {
                [tempArray removeObjectAtIndex:8];
                [tempArray removeObjectAtIndex:9];
                [tempArray removeObjectAtIndex:0];
                [tempArray removeLastObject];
            }
            self.collectionDataArray = [NSMutableArray arrayWithArray:tempArray];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                block();
            });
        }];
        [dataTask resume];
    });
}
#pragma mark - tabelView请求数据
- (void)requestFirstPartyDataWithUrl:(NSString *)url block:(void (^)(NSArray *array))block
{
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]  cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30];
        [request setHTTPMethod:@"GET"];
        
        NSURLSessionConfiguration *config = [NSURLSessionConfiguration ephemeralSessionConfiguration];
        NSURLSession *session = [NSURLSession sessionWithConfiguration:config];
        NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            
            if (data == nil) {
                return ;
            }
            
            NSDictionary *rootDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            NSArray *array = rootDic[@"result"];
            
            NSMutableArray *tempArray = [NSMutableArray array];
            for (NSDictionary *dic in array) {
                PartyModel *model = [[PartyModel alloc] init];
                [model setValuesForKeysWithDictionary:dic];
                [tempArray addObject:model];
            }
            PartyModel *model = [tempArray firstObject];
            if ([model.item_type isEqualToString:@"event"]) {
                [tempArray removeObject:model];
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                block(tempArray);
            });
        }];
        [dataTask resume];
    });
}





- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
